<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace app\worker;

use app\model\UserModel;
use GatewayWorker\Lib\Gateway;
use Workerman\Worker;
use think\worker\Application;


/**
 * Worker 命令行服务类
 */
class Events
{
    /**
     * onWorkerStart 事件回调
     * 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次
     *
     * @access public
     * @param  \Workerman\Worker    $businessWorker
     * @return void
     */
    public static function onWorkerStart(Worker $businessWorker)
    {
        $app = new Application;
        $app->initialize();
    }

    /**
     * onConnect 事件回调
     * 当客户端连接上gateway进程时(TCP三次握手完毕时)触发
     *
     * @access public
     * @param  int       $client_id
     * @return void
     */
    public static function onConnect($client_id)
    {
        // 发送init请求；
        Gateway::sendToClient($client_id,json_encode([
            'type'=>'init',
            'client_id'=>$client_id
        ]));

       // Gateway::sendToCurrentClient("Your client_id is $client_id");
    }


    /**
     * onWebSocketConnect 事件回调
     * 当客户端连接上gateway完成websocket握手时触发
     *
     * @param  integer  $client_id 断开连接的客户端client_id
     * @param  mixed    $data
     * @return void
     */
    public static function onWebSocketConnect($client_id, $data)
    {
        //var_export($data);
    }

    /**
     * onMessage 事件回调
     * 当客户端发来数据(Gateway进程收到数据)后触发
     *
     * @access public
     * @param  int       $client_id
     * @param  mixed     $data
     * @return void
     */
    public static function onMessage($client_id,$data)
    {
        // Gateway::sendToAll($data);
        $arr = json_decode($data);

        // 绑定
        if($arr->type == "bind"){

            $user_id = UserModel::getUseridByToken($arr->token);
            Gateway::bindUid($client_id, $user_id);

            $msg = ["type"=>"bind", "data" => "success to bind!!"];
            Gateway::sendToClient($client_id, json_encode($msg));

        }

//        刷新数据
        if($arr->type == "flush"){
            $msg = ["type"=>"flush"];
            GateWay::sendToAll(json_encode($msg));
        }


        /*
            只要是发消息，就把相关数据保存到库（通过调用接口的方式）
        */

//        // 聊天 一对一
//        if($arr->type == "text"){
//            /*
//                1、用户在线
//                    发送消息（已读，未读） - 保存到数据库并标记已读（不建议）
//                2、用户不在线
//                    发送消息（已读，未读） - 保存到数据库并标记未读
//
//                给用户发消息，用户收到消息后，再反馈给服务器，然后再标记消息已读
//            */
//            Gateway::sendToUid($arr->to_user_id,$data);
//        }

    }

    /**
     * onClose 事件回调 当用户断开连接时触发的方法
     *
     * @param  integer $client_id 断开连接的客户端client_id
     * @return void
     */
    public static function onClose($client_id)
    {
        //GateWay::sendToAll("client[$client_id] logout\n");
        $msg = ["type"=>"message","message"=>"用户client[$client_id] logout下线了"];
        GateWay::sendToAll(json_encode($msg));
    }

    /**
     * onWorkerStop 事件回调
     * 当businessWorker进程退出时触发。每个进程生命周期内都只会触发一次。
     *
     * @param  \Workerman\Worker    $businessWorker
     * @return void
     */
    public static function onWorkerStop(Worker $businessWorker)
    {
        echo "WorkerStop\n";
    }
}
